#! /usr/bin/env python3
# - check_name
# - owner
# - repo
# - pr_num
# - conf

# access-check

import os
import sys
sys.path.append(
    os.path.join(os.getenv("LKP_SRC"), "programs/access-check"))

import logging
logger = logging.getLogger('ac')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
logger.addHandler(handler)

from acl.check_binary_file import CheckBinaryFile
from acl.check_yaml import CheckPackageYaml
from acl.check_license import CheckLicense
from acl.check_spec import CheckSpec

from utils.git_proxy import GitProxy
from framework.ac_result import ACResult

# 暂时的实现，后续正式适配后修改
mapping = {
    'check_binary_file': CheckBinaryFile,
    'check_spec': CheckSpec,
    'check_package_license': CheckLicense,
    'check_package_yaml_file': CheckPackageYaml,
}

workspace = os.getenv('TMP')
check_name = os.getenv('check_name')
account = os.getenv('secrets_git_account')
password = os.getenv('secrets_git_password')
owner = os.getenv('owner')
repo = os.getenv('repo')
pr_num = os.getenv('pr_num')
conf = os.getenv('conf')
job_id = os.getenv('id')
result_root = os.getenv('result_root')

logger.info("using credential %s", account)
logger.info("cloning repository https://gitee.com/%s/%s.git ", owner, repo)
logger.info("clone depth 4")
logger.info("checking out pull request https://gitee.com/%s/%s/pulls/%s", owner, repo, pr_num)

if password: accout = f"{account}:{password}"

git_proxy = GitProxy.init_repository(
    repo, work_dir=workspace)
repo_url = "https://{}@gitee.com/{}/{}.git".format(
    account, owner, repo)

if not git_proxy.fetch_pull_request(repo_url, pr_num, depth=4):
    logger.error("fetch finished -")
    sys.exit(-1)
else:
    git_proxy.checkout_to_commit_force("pull/{}/MERGE".format(pr_num))
    logger.info("fetch finished +") 

logger.info("--------------------AC START---------------------")

check = mapping[check_name](
    workspace=workspace,
    repo=repo,
    conf=conf
)

result = check()
logger.info(f"Result: {result}")
logger.info(f"job_id: {job_id}")
logger.info(f"result_root: {result_root}")

logger.info("--------------------AC DONE---------------------")
